package com.longe.config;

import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.ParameterBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.schema.ModelRef;
import springfox.documentation.service.ApiInfo;
import springfox.documentation.service.Parameter;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

@Configuration
@EnableSwagger2
@Data
@PropertySource(value = {"classpath:swagger2.properties"})
@ConfigurationProperties(prefix = "swagger2")
public class Swagger2Config {

    private String basePackage;

    private String title;

    private String description;

    private String serviceUrl;

    private String version;

    @Value("${swagger2.enable}")
    private boolean enable;

    @Bean
    public Docket api() {

        //自定义的两个header：token和languageType
        List<Parameter> pars = new ArrayList<>();
        ParameterBuilder token = new ParameterBuilder();
        token.name("token").description("验证token")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build(); //required = false 非必须的header
        ParameterBuilder languageType = new ParameterBuilder();
        languageType.name("languageType").description("语言")
                .modelRef(new ModelRef("string")).parameterType("header")
                .required(false).build();
        pars.add(token.build());
        pars.add(languageType.build());

        return new Docket(DocumentationType.SWAGGER_2)
                .enable(enable)
                .select()
                .apis(RequestHandlerSelectors.basePackage(basePackage))
                .paths(PathSelectors.any())
                .build()
                .globalOperationParameters(pars) //加入全局配置参数
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(title)
                .description(description)
                //服务条款网址
                .termsOfServiceUrl(serviceUrl)
                .version(version)
                .build();
    }
}
